/**
 * 
 */
package cn.com.ericsson;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import javax.swing.JOptionPane;

/**
 * @author edongxi
 *
 */
public class FileUtils {
	public static Vector<File> allFile = new Vector<File>(); //保存所有的isf文件
	 
	public static Map<String, String> filterMap = new HashMap<String, String>();
	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}
	
	/**
	  * 判断文件名是否非法
	  * @param fullPath 文件的全路径（路径加文件名）
	  * @return
	  */	
	public static boolean isPathIllegal(String fileName)
	{
		return fileName.matches(".*[[\u4e00-\u9fa5]\\s&()].*");
	}
	
	
	/**
	  * 获取文件路径
	  * @param fullPath 文件的全路径（路径加文件名）
	  * @return
	  */
	 public String getPath(String fullPath)
	 {
		 int index = fullPath.lastIndexOf(".");
		 String path = fullPath.substring(0, index-1);
		 return path;
	 }
	 
	 /**
	  * 将文件拷贝到指定目录
	  * @param folder 拷贝目录
	  * @param source 原始文件
	  */
	 public static void copyFile(File folder, File source)
	 {
		 String newPath = folder.getPath() + "\\" + source.getName();
		 try
		 {
			 int bytesum = 0;
			 int byteread = 0;
			 InputStream is = new FileInputStream(source);
			 FileOutputStream fos = new FileOutputStream(newPath);
			 byte[] buffer = new byte[1444];

			 while ((byteread = is.read(buffer)) != -1)
			 {
				 bytesum += byteread;
				 System.out.println(bytesum);
				 fos.write(buffer, 0, byteread);
			 }
			 is.close();
		 }
		 catch (Exception e)
		 {
			 System.out.println("Copy file error");
			 e.printStackTrace();
		 }
	 }
	 
	 /**
	  * 将文件剪切到指定目录
	  * @param folder 剪切目录
	  * @param source 原始文件
	  */
	 public static void moveTo(File folder, File source)
	 {
		 copyFile(folder, source);
		 source.delete();
	 }
	 
	 /**
	  * 获得文件的扩展名
	  * @param file
	  * @return 返回文件的扩展名
	  */
	 public static String getExtension(File file)
	 {
		 String extension = new String();
		 String name = file.getName();
		 int index = name.lastIndexOf('.');
		 if ((index > -1) && (index < name.length()-1))
		 {
			 extension = name.substring(index + 1);
		 }
		 return extension;
	 }
	 
	 /**
	  * 获得文件的名称（不包含扩展名）
	  * @param file
	  * @return 返回文件名字符串
	  */
	 public static String getFileName(File file)
	 {
		 String name = new String();
		 String fullName = file.getName();
		 int index = fullName.lastIndexOf('.');
		 name = fullName.substring(0, index+1);
		 return name;
	 }
	 
	 public static void changeChinesePath(File file)
	 {
		 normalizePathAndFile(file);
		 normalizePathAndFolder(file);
	 }
	 
	 /**
	  * 判断文件是否为isf文件
	  * @param file
	  * @return
	  */
	 public static boolean isIsf(File file)
	 {
		 if (file.isFile())
		 {
			 String extension = getExtension(file);
			 return extension.equalsIgnoreCase("isf");
		 }
		 else
		 {
			 return false;
		 }
	 }
	
	 /**
	  * 获得指定目录及其子目录下的所有isf文件
	  * @param folder 指定目录
	  * @return	有所的isf文件
	  */
	
	 public static Vector<File> getAllIsf(File folder)
	 {
		 File[] files = folder.listFiles();
		 int num = files.length;

		 for (int i=0; i<num; i++)
		 {
			 File f = files[i];
			 if (isIsf(f))
			 {
				 allFile.add(f);
			 }
			 else if (f.isDirectory())
			 {
				 getAllIsf(f);
			 }
		 }
		 
		 return allFile;
	 }
	 
	 
	 /**
	  * 从工程目录中读取配置文件，将需要过滤的字符串保存在static的Map中
	  */
	 public static void getFilterMap()
	 {
		 //String path = System.getProperty("user.dir");
		 //String fullPath = path + "\\config\\" + "config.txt";
		 String fullPath ="c:\\config.txt";
		 String[] keyValue = new String[2];
		 try
		 {
			 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fullPath),"utf-8"));
			 String line = null;
			 
			 System.out.println("\n################### Change illegal strings as follow ###################\n");
			 while ((line=br.readLine()) != null)
			 {
				 System.out.println(line);
				 keyValue = line.split("/");
				 filterMap.put(keyValue[0],keyValue[1]);
			 }
			 filterMap.put("\\(", "_");
			 filterMap.put("\\)", "_");
			 br.close();
		 }
			 catch (Exception e)
			 {
				 e.printStackTrace();
			 }
	 } 
	 
	 public static String str2Normal(String str)
	 {
		 Set<String> filter = filterMap.keySet();
		 String key = null;

		 int index = 0;
		 
		 if (isPathIllegal(str))
		 {
			 for (Iterator<String> it=filter.iterator(); it.hasNext();)
				{	
					key = it.next();
					index = str.indexOf(key);
					
					if (index > -1)
					{
						if(key.equals("(")||key.equals(")")){
							key = "\\" + key;
						}
						str = str.replaceAll(key, filterMap.get(key));
					}			
				}
				
				 str = CnToPy.getPinYinHeadChar(str);

		 }
		 
		 return str;
	 }
	 
	 /**
	  * 判断该File是否为isf文件，或是否包含isf文件
	  * @param root 根目录
	  * @return
	  */
	 public static boolean isOrContaionIsf(File root)
	 {
		 boolean flag = false; 
		 File[] childs = root.listFiles();
		 int childNum = 0;
		 File child = null;
		 
		 if (root.isFile())
		 {
			 if (isIsf(root))
			 {
				 return true;
			 }
		 }
		 else
		 {
			 childs = root.listFiles();
			 childNum = childs.length;
			 
			 for (int i=0; i<childNum; i++)
			 {
				 child = childs[i];
				 
				 if (isIsf(child))
				 {
					 flag = true;
				 }
				 else if (!child.isDirectory())
				 {
					 flag = false;
				 }
				 else
				 {
					 isOrContaionIsf(child);
				 }
			 }
			 
			 isOrContaionIsf(child);
		 }
		 
		 return flag;
	 }
	 
	 /**
	  * 判断目录或其子目录中是否含有isf文件
	  * @param root 根目录
	  * @return
	  */
	 public static boolean containIsf(File root)
	 {
		 boolean flag = false;
		 File[] childs = root.listFiles();
		 File child = null;
		 int childNum = childs.length;
		 
		 for (int i=0; i<childNum; i++)
		 {
			 child = childs[i];
			 
			 if (isIsf(child))
			 {
				 flag = true;
			 }
			 else if (!child.isDirectory())
			 {
				 flag = false;
			 }
			 else
			 {
				 containIsf(child);
			 }
		 }
		 return flag;
	 }
	 
	 
	 public static void normalizePathAndFile(File root)
	 {
		 Set<String> filter = filterMap.keySet();
		 String key = null;

		 File file = null;
		 int index = 0;
		 File[] childs = root.listFiles();
		 int childNum = 0;
		 
		 if (childs == null) //root为终端节点
		 {
			 JOptionPane.showMessageDialog(null, "the folder is empty, please change a folder!", "Confirmation Message", JOptionPane.INFORMATION_MESSAGE);
		 }
		 else //非终端节点，即有子目录或子文件的文件夹
		 {
			 childNum = childs.length;
			 for(int i=0;i<childs.length;i++){
				 if(childs[i].isDirectory()){
					 normalizePathAndFile(childs[i]);
				 }else if(isIsf(childs[i])){
//以为应为将isf文件改名。
					 String name=childs[i].getName();
					 String newName;
					 for (Iterator<String> it=filter.iterator(); it.hasNext();)
					 {
						 key = it.next();
						 index = name.indexOf(key);
					
						 if (index > -1)
						 {
							 if(key.equals("(")||key.equals(")"))
							 {
								 if (key.equals("(")||key.equals(")"))
								 {
									 key = "\\" + key;
								 }
							 }
								
							 name = name.replaceAll(key, filterMap.get(key));
						 }
					 }
				 		
					 newName = CnToPy.getPinYinHeadChar(name);
					 newName = childs[i].getParent() + "\\" + newName;
					 File targetfile = new File(newName);
					 childs[i].renameTo(targetfile);
					
				 }
			 }
			 		 
		
		 }
	 }
	 
	 public static void normalizePathAndFolder(File root)
	 {
		 Set<String> filter = filterMap.keySet();
		 String key = null;

		 File file = null;
		 int index = 0;
		 File[] childs = root.listFiles();
		 int childNum = 0;
		 
		 if (childs == null) //root为终端节点
		 {
			 JOptionPane.showMessageDialog(null, "the folder is empty, please change a folder!", "Confirmation Message", JOptionPane.INFORMATION_MESSAGE);
		 }
		 else //非终端节点，即有子目录或子文件的文件夹
		 {
			 childNum = childs.length;
			 for(int i=0;i<childs.length;i++){
				 if(childs[i].isDirectory()){
					 String name=childs[i].getName();
					 String newName;
					 for (Iterator<String> it=filter.iterator(); it.hasNext();)
					 {
						 key = it.next();
						 index = name.indexOf(key);
					
						 if (index > -1)
						 {
							 if(key.equals("(")||key.equals(")"))
							 {
								 if (key.equals("(")||key.equals(")"))
								 {
									 key = "\\" + key;
								 }
							 }
								
							 name = name.replaceAll(key, filterMap.get(key));
						 }
					 }
				 		
					 newName = CnToPy.getPinYinHeadChar(name);
					 newName = childs[i].getParent() + "\\" + newName;
					 File targetfile = new File(newName);
					 childs[i].renameTo(targetfile);
					
				 }
			 }			 		 		
		 }
	 }

	 /*
	 public static void normalizePathAndFile(File sroot)
	 {
		 Set<String> filter = filterMap.keySet();
		 String key = null;
		 File root = new File(sroot.getPath());
		 String name = root.getName();
		 String newName = null;
		 File file = null;
		 int index = 0;
		 File[] childs = root.listFiles();
		 int childNum = 0;
		 
		 if (childs == null) //root为终端节点
		 {
			 if (isIsf(root) && isPathIllegal(name))
			 {
				 //如果root是终端节点，那么root是非法的isf文件时转换
				 
				 for (Iterator<String> it=filter.iterator(); it.hasNext();)
				 {
					 key = it.next();
					 index = name.indexOf(key);
					 
					 if (index > -1)
					 {
						 if(key.equals("(")||key.equals(")"))
						 {
							 if (key.equals("(")||key.equals(")"))
							 {
								 key = "\\" + key;
							 }
						 }
							
						 name = name.replaceAll(key, filterMap.get(key));
					 }
				 }
			 		
				 newName = CnToPy.getPinYinHeadChar(name);
//				 newName = root.getPath() + "\\" + newName;
				 newName = root.getParent() + "\\" + newName;
				 file = new File(newName);
				 
				 if (root.renameTo(file))
				 {
					 root = file;
				 }
			 }
		 }
		 else //非终端节点，即有子目录或子文件的文件夹
		 {
			 childNum = childs.length;
			 		 
			 if (containIsf(root) && isPathIllegal(name)) //该目录包含isf文件，且目录的路径非法
			 {
				 for (Iterator<String> it=filter.iterator(); it.hasNext();)
				 {
					 key = it.next();
					 index = name.indexOf(key);
					 
					 if (index > -1)
					 {
						 if(key.equals("(")||key.equals(")"))
						 {
							 if (key.equals("(")||key.equals(")"))
							 {
								 key = "\\" + key;
							 }
						 }
							
						 name = name.replaceAll(key, filterMap.get(key));
					 }
				 }
			 		
				 newName = CnToPy.getPinYinHeadChar(name);
//				 newName = root.getPath() + "\\" + newName;
				 newName = root.getParent() + "\\" + newName;
				 file = new File(newName);
				 
				 if (root.renameTo(file))
				 {
					 root = file;
				 }
				 
				 for (int i=0; i<childNum; i++)
				 {
					 normalizePathAndFile(childs[i]);
				 }
				 				 
			 }
			 else if (containIsf(root) && !isPathIllegal(name)) //该目录包含isf文件，且目录的路径合法
			 {
				 for (int i=0; i<childNum; i++)
				 {
					 normalizePathAndFile(childs[i]);
				 }
				 
			 }
		 }
	 }
	 */
	 
	 /*
	 public static void normalizePathAndFile(File root)
	 {
		 File[] childs = root.listFiles();
		 
		 
		 
		 
		 int childNum = childs.length;
		 String name = null;
		 String newName = null;
		 File child = null;
		 File file = null;
		 Set<String> filter = filterMap.keySet();
		 String key = null;
		 int index = 0;
		 int totalchanged = 0;
		 
		 
		 for (int i=0; i<childNum; i++)
		 {
			 child = childs[i];
			 name = child.getName();
			 
			 if (isPathIllegal(name))
			 {
				 if (child.isDirectory()) // 如果是非法文件夹
				 {
					 for (Iterator<String> it=filter.iterator(); it.hasNext();)
					 {
						 key = it.next();
						 index = name.indexOf(key);
						 
						 if (index > -1)
						 {
							 if(key.equals("(")||key.equals(")"))
							 {
								 if (key.equals("(")||key.equals(")"))
								 {
									 key = "\\" + key;
								 }
							 }
								
							 name = name.replaceAll(key, filterMap.get(key));
						 }
					 }
				 		
					 newName = CnToPy.getPinYinHeadChar(name);
					 newName = root.getPath() + "\\" + newName;
					 file = new File(newName);
					 
					 if (child.renameTo(file))
					 {
						 child = file;
					 }
					 
					 normalizePathAndFile(child);
				 }
				 
				 else // 合法文件夹或文件
				 {
					 if (isIsf(child)) //如果是非法文件
					 {
						 for (Iterator<String> it=filter.iterator(); it.hasNext();)
						 {
							 key = it.next();
							 index = name.indexOf(key);
							 
							 if (index > -1)
							 {
								 if(key.equals("(")||key.equals(")"))
								 {
									 if (key.equals("(")||key.equals(")"))
									 {
										 key = "\\" + key;
									 }
								 }
									
								 name = name.replaceAll(key, filterMap.get(key));
							 }
						 }
					 		
						 newName = CnToPy.getPinYinHeadChar(name);
						 newName = root.getPath() + "\\" + newName;
						 file = new File(newName);
						 
						 if (child.renameTo(file))
						 {
							 child = file;
						 }
					 }
					 
					 else
					 {
						 normalizePathAndFile(child);
					 }
				 }
			 }
		 }
	 }
	*/ 
	 
	 
	 
	 
	 public static boolean isThereChinese(String name)
	 {
		 String result = CnToPy.getPingYin(name);
		 
		 if (result.equals(name))
		 {
			 return false;
		 }
		 else
		 {
			 return true;
		 }
	 }
	
	/**
	 * 将文件名中的非法字符（除字母，数字，-,_,%外的）用"_"替换。
	 * @param files 文件集合
	 */
	public static void changeIsfName(Vector<File> files)
	{
		String name = null;
		String key = null;
		String newName = null;
		File file = null;
		String normalizedName = null;
		Set<String> filter = filterMap.keySet();
		int totalchanged = 0;	
		int index = 0;
		
		for (int i=0; i<files.size(); i++)
		{
			file = files.get(i);
			name = file.getName();
			
			if (isPathIllegal(name))
			{
				newName = str2Normal(name);
				newName = file.getParent() + "\\" + newName;
				file.renameTo(new File(newName));
				
				if (file.isDirectory())
				{
//					changeIsfName(file);
				}
				
			}
			else
			{
				
			}
		}
		
		
//		LogPreDeal.tableData.clearData();
//		
//		for (int i=0; i<files.size(); i++)
//		{
//			file = files.get(i);
//			name = file.getName();
//			
//			if (isPathIllegal(name))
//			{		
//				System.out.print(name + " ----> ");
//				
//				for (Iterator<String> it=filter.iterator(); it.hasNext();)
//				{
//					
//					key = it.next();
//					index = name.indexOf(key);
//					
//					if (index > -1)
//					{
//						if(key.equals("(")||key.equals(")")){
//							key = "\\" + key;
//						}
//						name = name.replaceAll(key, filterMap.get(key));
//					}			
//				}
//				
//				File newFile = new File(file.getParent() + "\\" + name);
//				file.renameTo(newFile);
//				
//				totalchanged++;
//				System.out.println(name);		
//				LogPreDeal.tableData.addText(file.getPath());
//			}
//			else
//			{
//				LogPreDeal.tableData.addText(file.getPath());
//				System.out.println(name + " doesn't need normalizing!");
//			}
//		}	
		
		System.out.println("################### " + totalchanged + " isf file names has changed" + " ###################\n");
	}
	
}
